<template>
    <el-form
        :model="goodForm"
        ref="goodFormRef"
        :rules="rules"
        label-width="80px"
    >
        <el-form-item label="用户名称">
            <el-input v-model="goodForm.shop"></el-input>
        </el-form-item>
        <!-- <el-form-item label="昵称" prop="product"> -->
        <el-form-item label="昵称">
            <el-input v-model="goodForm.product"></el-input>
        </el-form-item>
        <el-form-item label="密码">
            <el-input v-model="goodForm.price"></el-input>
        </el-form-item>

        <el-form-item label="权限等级">
            <el-select
                v-model="goodForm.categoryId"
                clearable
                placeholder="权限"
            >
                <el-option
                    v-for="item in category"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
            </el-select>
        </el-form-item>


        <!-- <el-form-item label="原价">
            <el-input v-model="goodForm.oldprice"></el-input>
        </el-form-item> -->
        <el-form-item label="图片">
            <!-- 
                list-type: picture-card 卡片样式
                action: 图片上传url地址
                auto-upload: 是否自动上传，true自动上传，选中图片直接上传到action指定url
                show-file-list: false单文件上传，true支持多文件上传
                before-upload: 上传前回调, 当前auto-upload为true时执行,回调函数中返回false终止上传
             -->
            <el-upload
                list-type="picture-card"
                action="#"
                :auto-upload="true"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
            >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else><Plus /></el-icon>
            </el-upload>
        </el-form-item>

        <!-- <el-form-item label="上下架">
            <el-radio-group v-model="goodForm.putaway">
                <el-radio :label="1">上架</el-radio>
                <el-radio :label="0">下架</el-radio>
            </el-radio-group>
        </el-form-item> -->

        <el-form-item>
            <el-button type="primary" @click="onSubmit">确定</el-button>
            <el-button type="primary" @click="onClose">关闭</el-button>
        </el-form-item>

    </el-form>
</template>

<script lang="ts">
import {
    // RequestCatgoryList,
    // RequestAddGoods,
    // RequestUpdateGoods,
} from '@/api/index'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {baseURL} from '@/utils/request'
import axios from 'axios'
export default {
    components: {
        Plus,
    },
    props: ['goods', 'type'],
    emits: ['close'],
    data() {
        return {
            goodForm: {
                shop: '',
                product: '',
                price: '',
                oldprice: '',
                picture: '',
                putaway: 1,
                categoryId: '',
            },
            category: [],
            rules: {
                product: [
                    {
                        required: true,
                        message: '请输入产品名称',
                        trigger: 'blur',
                    },
                ],
            },
            imageUrl: '', //图片预览地址
            imageFile: null, //上传图片文件
        }
    },
    created() {
        if(this.type === 'EDIT'){
            this.goodForm = { ...this.goods }
            this.imageUrl = this.filterUrl(this.goodForm.picture)
        }
        this.getCategoryList()
    },
    methods: {
        filterUrl(url) {
            return url?.indexOf('http') === -1
                ? baseURL + url
                : url
        },
        /**
         * 分类列表
         */
        async getCategoryList() {
            this.category = [
                {id:1,name:'超级管理员'},
                {id:2,name:'订单管理员'},
                {id:3,name:'商品管理员'},
            ]
        },
        /**
         * 保存产品
         *  图片上传http注意事项
         *     1. post请求
         *     2. 请求头header 上传内容类型 content-type:multipart/form-data
         *         headers: { 'Content-Type': 'multipart/form-data' },
         *     3. FormData
         *         const formData = new FormData()
         *         formData.append('product',product)
         *         formData.append('picture',file)
         */
        async onSubmit() {
            const formData = new FormData()
            formData.append('myfile', this.imageFile)
            formData.append('categoryId', this.goodForm.categoryId)
            formData.append('product', this.goodForm.product)
            formData.append('shop', this.goodForm.shop)
            formData.append('price', this.goodForm.price)
            // formData.append('oldprice', this.goodForm.oldprice)
            // formData.append('putaway', this.goodForm.putaway)
            
            let res
            // // 编辑
            if (this.type === 'EDIT') {
                formData.append('id', this.goodForm.id)
                res = await axios({
                    method:"post",
                    url:'http://localhost:3000/operator/edit',
                    headers: { 'content-type': 'multipart/form-data' },
                    data:formData
                })
            }else{
                res = await axios({
                    method:"post",
                    url:'http://localhost:3000/operator/add',
                    headers: { 'content-type': 'multipart/form-data' },
                    data:formData
                })
            }
            
            const { code } = res.data
            if (code === 1) {
                ElMessage({
                    message: this.type === 'EDIT'?'编辑成功!':'添加成功!',
                    type: 'success',
                })
                this.onClose()
            }
        },
        onClose() {
            this.$emit('close')
        },
        /**
         * 文件上传之前执行
         * @param {*} rawFile
         */
        beforeAvatarUpload(rawFile) {
            const arr = ['image/jpeg', 'image/png', 'image/jpg']
            // 图片格式验证
            if (!arr.includes(rawFile.type)) {
                ElMessage({
                    message: '上传图片格式不正确！!',
                    type: 'error',
                })
                return false
            }
            // 图片大小验证
            if (rawFile.size / 1024 / 1024 > 2) {
                ElMessage({
                    message: '上传图片大小不能超过2M!',
                    type: 'error',
                })
                return false
            }

            // 图片预览
            //1. 选中的本地图片转成Base64编码 赋值给 imageUrl
            //2. FileReader 读文件
            this.imageUrl = URL.createObjectURL(rawFile)

            // 上传图片
            this.imageFile = rawFile
            return false // 不向下执行
        },
    },
}
</script>

<style lang="scss" scoped>
.avatar {
    width: 150px;
    height: 150px;
    display: block;
}
</style>
